﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Aspose.Cells;
using System.Data;
using XMK.Tadong.Biz;
using XMK.Framework.Model;
using XMK.Utils;
using System.Collections.Specialized;
using System.Text;
using XMK.Tadong.Model;

namespace XMK.Tadong.Web
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            

           // NameValueCollection nc = HttpUtility.ParseQueryString(Request.Url.Query, Encoding.GetEncoding("GB2312"));
            //string kw = nc["kw"]; 
            string kw = MyUrlDeCode(Request.QueryString["kw"],null);
            string proc = Request.QueryString["proc"];
            //添加日志
            string ip = Request.ServerVariables["REMOTE_ADDR"].Equals("::1") ? "127.0.0.1" : Request.ServerVariables["REMOTE_ADDR"];
            string tableName = proc.Substring(proc.LastIndexOf("_")+1);
            XMKLogBiz.WriteLogExcel(tableName,ip);
            PageInfo page = new PageInfo();
            page.PageSize = 2000;
            page.CurrentPage = 1;// ParseHelper.Parse<int>(context.Request.Params.Get("page"));
            OrderInfo order = new OrderInfo();
            order.ColName = "jh";
            order.Sort = "asc";
            V_Base_Struct_KeywBiz biz = new V_Base_Struct_KeywBiz();
            ResponseInfo resp = biz.QueryTableData(proc,
               kw, page, order
                );

            DataTable dt = (System.Data.DataTable) resp.Data;
            //dt.Columns[""].Caption=""
            //System.Data.DataTable dt = new System.Data.DataTable();
            //MakeTable(dt);
            ExportExcelWithAspose( (System.Data.DataTable) resp.Data, "", Response);//(System.Data.DataTable)resp.Data


        }

        public static string MyUrlDeCode(string str, Encoding encoding)
        {
            if (encoding == null)
            {
                Encoding utf8 = Encoding.UTF8;
                //首先用utf-8进行解码                    
                string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
                //将已经解码的字符再次进行编码.
                string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
                if (str == encode)
                    encoding = Encoding.UTF8;
                else
                    encoding = Encoding.GetEncoding("gb2312");
            }
            return HttpUtility.UrlDecode(str, encoding);
        }

      

        public static bool ExportExcelWithAspose(System.Data.DataTable dt, string path, HttpResponse res)
        {
            bool succeed = false;
            if (dt != null)
            {
                try
                {
                    //Aspose.Cells.License li = new Aspose.Cells.License();
                    //string lic = Resources.License;
                    //Stream s = new MemoryStream(ASCIIEncoding.Default.GetBytes(lic));
                    //li.SetLicense(s);

                    Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
                    Aspose.Cells.Worksheet cellSheet = workbook.Worksheets[0];

                    cellSheet.Name = dt.TableName;

                    int rowIndex = 0;
                    int colIndex = 0;
                    int colCount = dt.Columns.Count;
                    int rowCount = dt.Rows.Count;

                    //列名的处理
                    //V_Base_Struct_KeywBiz biz = new V_Base_Struct_KeywBiz();
                    //List<BaseTableColumnDictInfo> listColum = biz.QueryTableColumnList1("AZ01");// biz.QueryTableColumnList(context.Request.Params.Get("tab_code"));
                    //foreach (BaseTableColumnDictInfo colum in listColum)
                    //{
                    //    cellSheet.Cells[rowIndex, colIndex].PutValue(colum.FIELD_NAME);
                    //}

                    for (int i = 0; i < colCount; i++)
                    {
                        cellSheet.Cells[rowIndex, colIndex].PutValue(dt.Columns[i].ColumnName);
                        // cellSheet.Cells[rowIndex, colIndex].Style.Font.IsBold = true;
                        // cellSheet.Cells[rowIndex, colIndex].Style.Font.Name = "宋体";
                        colIndex++;
                    }

                    Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];
                    style.Font.Name = "Arial";
                    style.Font.Size = 10;
                    Aspose.Cells.StyleFlag styleFlag = new Aspose.Cells.StyleFlag();
                    cellSheet.Cells.ApplyStyle(style, styleFlag);

                    rowIndex++;

                    for (int i = 0; i < rowCount; i++)
                    {
                        colIndex = 0;
                        for (int j = 0; j < colCount; j++)
                        {
                            cellSheet.Cells[rowIndex, colIndex].PutValue(dt.Rows[i][j].ToString());
                            colIndex++;
                        }
                        rowIndex++;
                    }
                    cellSheet.AutoFitColumns();

                    res.Clear();
                    res.ContentType = "application/vnd.ms-excel";
                    res.AddHeader("Content-Disposition", "attachment;filename=Report.xls");
                    // workbook.    workbook.Worksheets[0].Cells[2, 1].Value.ToString())
                    // SaveOptions option =new SaveOptions();
                    //报错注视掉的。
                    workbook.Save("report.xls", SaveType.OpenInExcel, FileFormatType.Excel97To2003, res);
                    //  workbook.Worksheets[0].Cells[
                    // res.Write(  workbook.Worksheets[0].Cells[2, 1].Value.ToString());
                   
                    //res.End();
                    HttpContext.Current.ApplicationInstance.CompleteRequest();


                    //path = Path.GetFullPath(path);
                    //workbook.Save(path);
                    succeed = true;
                }
                catch (Exception ex)
                {
                    succeed = false;
                }
            }

            return succeed;
        }





    }
}